package com.dealin.writer.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.dealin.dealinlibs.dialog.DLDialog;
import com.dealin.dealinlibs.dialog.OnInputCompletedListener;
import com.dealin.writer.DataManager;
import com.dealin.writer.R;
import com.dealin.writer.bean.Project;
import com.dealin.writer.recyclerView.AdapterRecyclerView;
import com.toshiba.adapter.WidgetListener;

import java.util.ArrayList;

public class NovelListActivity extends AppCompatActivity implements View.OnClickListener {
    private Toolbar mToolbar;
    private RecyclerView mProjectListRecyclerView;
    private RelativeLayout mContentNovelList;
    private FloatingActionButton mFab;
    private AdapterRecyclerView adapterRecyclerView ;
    private DLDialog dialog;

    ArrayList<Project> projects = DataManager.getProjectList();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_novel_list);
        initView();
        Intent intent = new Intent(this, ChapterListActivity.class);
        startActivity(intent);
        dialog =new DLDialog(this);
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mProjectListRecyclerView = (RecyclerView) findViewById(R.id.projectList_recyclerView);
        mContentNovelList = (RelativeLayout) findViewById(R.id.content_novel_list);
        mFab = (FloatingActionButton) findViewById(R.id.fab);
        setData();
        mFab.setOnClickListener(this);
    }

    private void setData() {
        adapterRecyclerView = new AdapterRecyclerView(this);
        bindEvent();
        refresh();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fab:
                break;

        }
    }

    public void bindEvent() {
        ArrayList<WidgetListener> listeners = new ArrayList<>();


        //小说名，重命名小说
        listeners.add(new WidgetListener(R.id.projectNameTv, new WidgetListener.OnWidgetClickListener() {
            @Override
            public void onWidgetClick(View v, final int position) {
                dialog.showInput("重命名小说", "请输入新小说名", new OnInputCompletedListener() {
                    @Override
                    public void onInputCompleted(String[] result, TextInputLayout[] textInputLayout) {
                        try {
                            projects.get(position).setName(result[0]);
                            adapterRecyclerView.notifyDataSetChanged();
                            Toast.makeText(NovelListActivity.this, "重命名小说成功！", Toast.LENGTH_LONG).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(NovelListActivity.this, "重命名小说失败！", Toast.LENGTH_LONG).show();

                        }
                    }
                });
            }
        }, new WidgetListener.OnWidgetLongClickListener() {
            @Override
            public void onWidgetLongClick(View v,int position) {
                Toast.makeText(NovelListActivity.this,"重命名小说", Toast.LENGTH_SHORT).show();
            }
        }));


        //作者名，重命名作者
        listeners.add(new WidgetListener(R.id.projectAuthorTv, new WidgetListener.OnWidgetClickListener() {
            @Override
            public void onWidgetClick(View v, final int position) {
                dialog.showInput("重命名作者", "请输入新作者名", new OnInputCompletedListener() {
                    @Override
                    public void onInputCompleted(String[] result, TextInputLayout[] textInputLayout) {
                        try {
                            projects.get(position).setAuthor(result[0]);
                            adapterRecyclerView.notifyDataSetChanged();
                            Toast.makeText(NovelListActivity.this, "重命名作者成功！", Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(NovelListActivity.this, "重命名作者失败！", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }, new WidgetListener.OnWidgetLongClickListener() {
            @Override
            public void onWidgetLongClick(View v,int position) {
                Toast.makeText(NovelListActivity.this,"重命名作者", Toast.LENGTH_SHORT).show();
            }
        }));


        //导出图标
        listeners.add(new WidgetListener(R.id.projectOutputIv, new WidgetListener.OnWidgetClickListener() {
            @Override
            public void onWidgetClick(View v,int position) {
                try {
                    projects.get(position).outputNovel();
                    dialog.showMessege("导出小说为TXT","小说《"+projects.get(position).getName()+"》已导出到sdcard/唯美小说/目录下！快去看看吧。");

                } catch (Exception e) {
                    dialog.showMessege("导出小说为TXT","小说《"+projects.get(position).getName()+"》导出失败。\n错误原因："+e.getLocalizedMessage());
                    e.printStackTrace();
                }
            }
        }, new WidgetListener.OnWidgetLongClickListener() {
            @Override
            public void onWidgetLongClick(View v,int position) {
                Toast.makeText(NovelListActivity.this,"导出小说为TXT", Toast.LENGTH_SHORT).show();
            }
        }));


        //小说详情图标
        listeners.add(new WidgetListener(R.id.projectInfoIv, new WidgetListener.OnWidgetClickListener() {
            @Override
            public void onWidgetClick(View v,int position) {
                dialog.showMessege("小说详情",projects.get(position).getProjectDetail());
            }
        }, new WidgetListener.OnWidgetLongClickListener() {
            @Override
            public void onWidgetLongClick(View v,int position) {
                Toast.makeText(NovelListActivity.this,"小说详情", Toast.LENGTH_SHORT).show();
            }
        }));


        //小说配置图标
        listeners.add(new WidgetListener(R.id.projectSetIv, new WidgetListener.OnWidgetClickListener() {
            @Override
            public void onWidgetClick(View v,int position) {
                //TODO：小说属性配置
            }
        }, new WidgetListener.OnWidgetLongClickListener() {
            @Override
            public void onWidgetLongClick(View v,int position) {
                Toast.makeText(NovelListActivity.this,"小说属性配置，尚未开发！", Toast.LENGTH_SHORT).show();
            }
        }));


        //小说加密图标
        listeners.add(new WidgetListener(R.id.projectLockIv, new WidgetListener.OnWidgetClickListener() {
            @Override
            public void onWidgetClick(View v, final int position) {
                //TODO:加密小说
                dialog.showModifyPassword("修改小说密码", "原密码（无密码请留空）", "新密码", "确认密码", new OnInputCompletedListener() {
                    @Override
                    public void onInputCompleted(String[] result, TextInputLayout[] textInputLayout) {
                        if (result[0].equals(projects.get(position).getPassword())) {
                            if (result[1].equals(result[2])) {
                                try {
                                    projects.get(position).setPassword(result[1]);
                                    Toast.makeText(NovelListActivity.this, "修改密码成功！", Toast.LENGTH_SHORT).show();
                                } catch (Exception e) {
                                    dialog.showMessege("修改密码时出错：" + e.getMessage());
                                    e.printStackTrace();
                                }

                            } else {
                                textInputLayout[2].setError("两次输入的密码不一致哦");
                            }
                        } else {
                            textInputLayout[0].setError("原密码输入错误");
                        }
                        Toast.makeText(NovelListActivity.this, projects.get(position).getPassword(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }, new WidgetListener.OnWidgetLongClickListener() {
            @Override
            public void onWidgetLongClick(View v,int position) {
                Toast.makeText(NovelListActivity.this,"小说加密", Toast.LENGTH_SHORT).show();
            }
        }));


        //网络备份图标
        listeners.add(new WidgetListener(R.id.projectBackupIv, new WidgetListener.OnWidgetClickListener() {
            @Override
            public void onWidgetClick(View v,int position) {
                //TODO:网络备份
                Toast.makeText(NovelListActivity.this, "等待开发……", Toast.LENGTH_SHORT).show();
            }
        }, new WidgetListener.OnWidgetLongClickListener() {
            @Override
            public void onWidgetLongClick(View v,int position) {
                Toast.makeText(NovelListActivity.this,"网络备份", Toast.LENGTH_SHORT).show();
            }
        }));


        //删除小说图标
        listeners.add(new WidgetListener(R.id.projectDel, new WidgetListener.OnWidgetClickListener() {
            @Override
            public void onWidgetClick(View v, final int position) {
                try {
                    dialog.showMessege("删除小说", "是否删除小说：" + projects.get(position).getName() + "？", "残忍删除", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            projects.get(position).delete();
                            projects.remove(position);
                            adapterRecyclerView.notifyItemRemoved(position);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    refresh();
                                }
                            }, position==projects.size()?0:450);
                            //refresh();
                            //adapterRecyclerView.notifyDataSetChanged();
                            Toast.makeText(NovelListActivity.this, "删除成功！", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (Exception e) {
                    dialog.showMessege(e.getMessage());
                }
            }
        }, new WidgetListener.OnWidgetLongClickListener() {
            @Override
            public void onWidgetLongClick(View v,int position) {
                Toast.makeText(NovelListActivity.this,"删除小说", Toast.LENGTH_SHORT).show();
            }
        }));
        adapterRecyclerView.setListenerForWiget(listeners);
    }


    /**
     * 刷新小说列表
     * */
    public void refresh() {
        DataManager.refreshNovelList();
        projects = DataManager.getProjectList();
        if (projects != null) {
            adapterRecyclerView.setList(projects);
            mProjectListRecyclerView.setAdapter(adapterRecyclerView);
            mProjectListRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            DefaultItemAnimator animator = new DefaultItemAnimator();
            mProjectListRecyclerView.setItemAnimator(animator);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Toast.makeText(this, "menu", Toast.LENGTH_SHORT).show();
        getMenuInflater().inflate(R.menu.menu_novel_list, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            case R.id.action_new_novel:
                dialog.showInput("新建小说", "小说名", "笔名", new OnInputCompletedListener() {
                    @Override
                    public void onInputCompleted(String[] result, TextInputLayout[] textInputLayout) {
                        try {
                            Project project = new Project();
                            project.createNewNovel(result[0], result[1]);
                            refresh();
                            Toast.makeText(NovelListActivity.this, "新建小说成功！", Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                            dialog.showMessege("新建小说出错！错误："+e.getMessage());
                        }
                    }
                });
                break;
        }
        return true;
    }

}
